﻿namespace Way.Bus.WMS.ST.Controllers.YS
{
    using Way.Contract.Data;
    using System;
    using Way.Bus.Controllers;
    using Way.Bus.WMS.ST.Controllers.OutOrder;
    using Way.Bus.WMS.ST.Model;
    using Way.EAP.DataAccess.Entity;
    using Way.Contract.Data.ControllerData;
    using Way.EAP.DataAccess.Regulation;
    using System.Collections.Generic;
    using Way.Contract.MVC;
    using Way.EAP.DataAccess.Data;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;

    public class ST_PackListController : BusinessController
    {
        public ST_PackListController() : base(new ST_PackList())
        {
        }
        public override bool IsSubmit
        {
            get
            {
                return true;
            }
        }
        public override bool IsReviewedState
        {
            get
            {
                return true;
            }
        }
        public override bool IsClearAway
        {
            get
            {
                return false;
            }
        }
        protected override void OnInitViewChildItem(ModelData data, ItemData item)
        {
            base.OnInitViewChildItem(data, item);
            if (data.name.EndsWith("OutNotice"))
            {
                ST_OutReceiptController.InitOutNotice(data, item);
                if (item.IsField("WLGS") || item.IsField("WAYBILL") || item.IsField("RECEIPTPRINTNUM") || item.IsField("RECEIPTPRINTSTATE"))
                    item.visible = false;
                if (item.IsField("ReceiptState"))
                    item.title = "签收状态";
                if (item.IsField("STATE"))
                    item.visible = true;
            }
            if (data.name.EndsWith("Materials"))
            {
                ST_OutReceiptController.InitOutNoticeMaterials(data, item);
            }
            if (data.name.EndsWith("ST_PackList"))
            {
                if (item.IsField("TheDriver"))
                {
                    //选择司机时关联车牌号和手机号
                    item.foreign.rowdisplay.Add("CarNo", "CarNo");
                    item.foreign.rowdisplay.Add("PhoneCode", "Phone");
                }
                if (item.IsField("code"))
                    item.visible = false;
                if (item.IsField("IsDisable"))
                    item.visible = false;
                if (item.IsField("TOWHNO"))
                    item.title = "发货仓库";
            }
        }
        protected override void OnForeignIniting(Way.Contract.MVC.IModel model, InitData data)
        {
            if (this.fdata.foreignobject.EndsWith("ST_CarList"))
            {
                foreach (ItemData item in data.modeldata.childitem)
                    ST_CarController.InitCarList(data.modeldata, item);
            }
            else
                base.OnForeignIniting(model, data);
        }
        protected override void OnForeignLoading(Way.Contract.MVC.IModel model, loadItem item)
        {
            base.OnForeignLoading(model, item);
            if (this.fdata.foreignobject.EndsWith("ST_CarList"))
            {
                List<SQLWhere> list = new List<SQLWhere>();
                list.AddRange(item.whereList);
                ST_CarController.SearchDriceWhere(list);
                item.whereList = list.ToArray();
            }
            if (this.fdata.filedname == "TOWHNO")
            {
                SQLWhere w = new SQLWhere();
                w.ColumnName = "WHTYPE";
                w.Value = "0";
                List<SQLWhere> list = new List<SQLWhere>();
                list.AddRange(item.whereList);
                list.Add(w);
                item.whereList = list.ToArray();
            }
        }
        protected override ReadTable OnForeignLoad(Way.Contract.MVC.IModel model, Way.Contract.Data.ControllerData.loadItem item)
        {
            ReadTable table= base.OnForeignLoad(model, item);
            return table;
        }
        protected override string SubmitName
        {
            get
            {
                return "派车";
            }
        }
        protected override string ReviewedName
        {
            get
            {
                return "运输";
            }
        }
        protected override void OnAdding(ControllerBase.SaveEvent item)
        {
            base.OnAdding(item);
            ST_PackList pl = item.Item as ST_PackList;
            if (pl != null)
            {
                foreach (ST_OutNotice on in pl.PackListNotice)
                {
                    on.PackID = 0;
                    ((IEntityBase)on).StateBase = EntityState.Select;
                    on.PackID = pl.ID;
                }
            }
        }
        protected override void OnAdded(EntityBase item)
        {
            ST_PackList pl = item as ST_PackList;
            if (pl != null)
            {
                foreach (ST_OutNotice on in pl.PackListNotice)
                {
                    on.PackID = 0;
                    ((IEntityBase)on).StateBase = EntityState.Select;
                    on.PackID = pl.ID;
                }
            }
        }
        protected override void OnEditing(ControllerBase.SaveEvent item)
        {
            base.OnEditing(item);
            ST_PackList pl = item.Item as ST_PackList;
            if (pl != null)
            {
                foreach (ST_OutNotice on in pl.PackListNotice)
                {
                    on.PackID = 0;
                    ((IEntityBase)on).StateBase = EntityState.Select;
                    on.PackID = pl.ID;
                }
            }
        }
        protected override void OnSubmitData(Bus.Model.BasicInfo info)
        {
            ST_PackList pack = info as ST_PackList;
            if (pack != null)
            {
                pack.PackListNotice.DataAction = this.model.GetDataAction();
                pack.PackListNotice.GetData();
                if (pack.PackListNotice.Count == 0)
                {
                    throw new Exception("异常：派车单下未关联签收单，不能派车！");
                }
            }
            base.OnSubmitData(info);
        }
        protected override void OnReviewedData(Bus.Model.BasicInfo info)
        {
            ST_PackList pack = info as ST_PackList;
            if (pack != null)
            {
                pack.PackListNotice.DataAction = this.model.GetDataAction();
                pack.PackListNotice.GetData("STATE<>3");
                if (pack.PackListNotice.Count > 0)
                    throw new Exception("异常：派车单不能开始运输，还有未装车签收单！");
                pack.State = 3;
            }
            base.OnReviewedData(info);
        }
        protected override void OnSubmitUser(Bus.Model.BasicInfo info, Bus.Model.ProcessState state)
        {
            ST_PackList pl=this.ActionItem as ST_PackList;
            if(pl!=null)
            {
                state.WorkUser = pl.GetAppendPropertyValue("TheDriver").ToString();
                state.WorkUserID = pl.TheDriver;
            }
        }
        /// <summary>
        /// 签收单条码
        /// </summary>
        [WhereParameter]
        public string barcode { get; set; }
        /// <summary>
        /// 派车单ID
        /// </summary>
        [WhereParameter]
        public string packid { get; set; }
        /// <summary>
        /// 装车
        /// </summary>
        /// <param name="barcode">签收单条码</param>
        public string Loading()
        {
            try
            {
                //string tn = (new ST_OutNotice()).ToString();
                //string sql = "select * from " + tn + " where ReceiptCode='{0}'";
                //IDataAction action = this.model.GetDataAction();
                //DataTable table = action.GetDataTable(string.Format(sql, this.barcode));
                //if (table != null && table.Rows.Count > 0)
                //{ 
                
                //}
                EntityList<ST_OutNotice> list = new EntityList<ST_OutNotice>(this.model.GetDataAction());
                list.GetData("ReceiptCode='" + barcode + "' and PackID='" + packid + "'");
                if (list.Count > 0)
                {
                    ST_OutNotice on = list[0];
                    if (on.STATE < 2)
                    {
                        throw new Exception("异常：未完成出库，不能再装车！");
                    }
                    ST_PackList pack = on.GetForeignObject<ST_PackList>(this.model.GetDataAction());
                    if (on.STATE == 2)
                    {
                        on.STATE = 3;
                        if (pack.State > 1)
                            throw new Exception("异常：本派车单已装车完成，不能再装车！");
                        if (pack.TheDriver != this.user.ID)
                            throw new Exception("异常：装车人并非派车单指派司机，不能装车！");
                        if (pack.IsSubmited == false)
                            throw new Exception("异常：派车单据状态为未派车，不能装车！");
                        if (pack.State < 1)
                        {
                            pack.State = 1;
                            pack.PackDate = DateTime.Now;
                            EntityList<ST_PackList> packlist = new EntityList<ST_PackList>(this.model.GetDataAction());
                            packlist.Add(pack);
                            packlist.Save();
                        }
                        list.Save();
                        pack.PackListNotice.DataAction = this.model.GetDataAction();
                        pack.PackListNotice.GetData("STATE<3");
                        if (pack.PackListNotice.Count == 0)
                        {
                            pack.State = 2;
                            pack.PackDate = DateTime.Now;
                            EntityList<ST_PackList> packlist = new EntityList<ST_PackList>(this.model.GetDataAction());
                            packlist.Add(pack);
                            packlist.Save();
                        }
                    }
                    else
                    {
                        if (on.STATE == 3)
                        {
                            on.STATE = 2;
                            if (pack.State > 1)
                            {
                                pack.State = 1;
                                pack.PackDate = DateTime.Now;
                                EntityList<ST_PackList> packlist = new EntityList<ST_PackList>(this.model.GetDataAction());
                                packlist.Add(pack);
                                packlist.Save();
                            }
                            list.Save();
                            return "-1";
                        }

                    }
                    return pack.PackListNotice.Count.ToString();
                }
                else
                    throw new Exception("异常：本派车单下未找到条码为" + barcode + "的签收单，请重新扫描或咨询出库人员！");
            }
            catch (Exception err)
            {
                throw err;
            }
        }
        /// <summary>
        /// 卸货
        /// </summary>
        /// <param name="barcode"></param>
        public void UnLoading()
        {
            try
            {
                EntityList<ST_OutNotice> list = new EntityList<ST_OutNotice>(this.model.GetDataAction());
                list.GetData("ReceiptCode='" + barcode + "' and PackID='" + packid + "'");
                if (list.Count > 0)
                {
                    ST_OutNotice on = list[0];
                    if (on.STATE != 3)
                        throw new Exception("异常：" + barcode + "签收单不是装车状态，不能卸货！");
                    on.STATE = 4;
                    ST_PackList pack = on.GetForeignObject<ST_PackList>(this.model.GetDataAction());
                    if (pack.TheDriver != this.user.ID)
                        throw new Exception("异常：卸货人并非派车单指派司机，不能卸货！");
                    if (pack.State != 3)
                        throw new Exception("异常：派车单未开始运输，不能卸货！");
                    list.Save();
                    pack.PackListNotice.GetData("STATE=3");
                    if (pack.PackListNotice.Count == 0)
                        pack.State = 4;
                    EntityList<ST_PackList> packlist = new EntityList<ST_PackList>(this.model.GetDataAction());
                    packlist.Add(pack);
                    packlist.Save();
                }
            }
            catch (Exception err)
            {
                throw err;
            }
        }
        public class tccs
        {
            /// <summary>
            /// 派车单ID
            /// </summary>
            public int id { get; set; }
            public string x { get; set; }
            public string y { get; set; }
            public string code { get; set; }
            /// <summary>
            /// 状态 0=开始运输，1=运输中，2=暂停点,3=卸货，4=运输完成
            /// </summary>
            public int zt { get; set; }
        }
        [WhereParameter]
        public tccs ccc { get; set; }
        public string ys()
        {
            string ss = "";
            ss = TransportCoordinate(ccc.id, ccc.x, ccc.y, ccc.zt, ccc.code);
            if (string.IsNullOrEmpty(ss) && ccc.zt == 0)
                ss = "开始运输中";
            return ss;
        }
        /// <summary>
        /// 运输坐标更新
        /// </summary>
        /// <param name="id">派车单ID</param>
        /// <param name="x">经度</param>
        /// <param name="y">纬度</param>
        /// <param name="isxc">状态 0=开始运输，1=运输中，2=暂停点,3=卸货，4=运输完成</param>
        /// <param name="code">运单号</param>
        public string TransportCoordinate(int id, string x, string y, int isxc, string code)
        {
            string ss = "";
            string tn = this.model.ToString();
            string cn = "ST_TransportCoordinates";
            string zs = "select * from " + tn + " where id=" + id;
            string cs = "select * from " + cn + " where ParentID=" + id;
            string cins = "insert into " + cn + "(ParentID,TransportTime,x,y,DD,code) values ({0},getdate(),'{1}','{2}','{3}','{4}')";
            IDataAction action = this.model.GetDataAction();
            DataTable tb = action.GetDataTable(zs);
            string state = tb.Rows[0]["State"].ToString();
            string TheDriver = tb.Rows[0]["TheDriver"].ToString();
            if (tb != null && tb.Rows.Count > 0)
            {
                if (isxc == 0)
                {
                    if (TheDriver != this.user.ID)
                        throw new Exception("异常：运输人并非派车单指派司机，不能开始运输！");
                    if (state == "2" || state == "3")
                    {
                        if (state == "2")
                        {
                            string us = "update " + tn + " set state=3 where id=" + id;
                            action.Execute(us);
                            action.Execute(string.Format(cins, id, x, y, isxc, code));
                        }
                        else
                        {
                            action.Execute(string.Format(cins, id, x, y, 0, code));
                        }
                    }
                    else
                    {
                        throw new Exception("异常：" + tb.Rows[0]["code"].ToString() + "派车单状态不能运输！");
                    }
                }
                if (isxc == 1)
                {
                    string gs = "select id from " + cn + " where parentid=" + id + " and DD=1";
                    object obj = action.GetValue(gs);
                    if (obj != null && !string.IsNullOrEmpty(obj.ToString()))
                    {
                        string us = "update " + cn + " set x='" + x + "',y='" + y + "',TransportTime=getdate(),code='" + code + "' where id=" + obj.ToString();
                        action.Execute(us);
                    }
                    else
                        action.Execute(string.Format(cins, id, x, y, isxc, code));
                }
                if (isxc == 3)
                {
                    if (state != "3")
                        throw new Exception("异常：派车单非运输状态不能卸货！");
                    if (TheDriver != this.user.ID)
                        throw new Exception("异常：卸货人并非派车单指派司机，不能卸货！");
                    string xht = new ST_OutNotice().ToString();
                    string xhs = "select * from " + xht + " where ReceiptCode='" + code + "' and PackID=" + id;
                    DataTable xhtb = action.GetDataTable(xhs);
                    if (xhtb != null && xhtb.Rows.Count > 0)
                    {
                        string us = "update " + xht + " set STATE=4 where id=" + xhtb.Rows[0]["id"].ToString();
                        action.Execute(us);
                        action.Execute(string.Format(cins, id, x, y, 2, code));
                        string sql = "select count(1) cont from " + xht + " where PackID=" + id + " and STATE<4";
                        object con = action.GetValue(sql);
                        if (con != null && !string.IsNullOrEmpty(con.ToString()))
                        {
                            if (con.ToString() == "0")
                            {
                                string us1 = "update " + tn + " set state=4 where id=" + id;
                                action.Execute(us1);
                                action.Execute(string.Format(cins, id, x, y, 3, code));
                                return "派车单运输完成。";
                            }
                            else
                            {
                                return "卸货完成，待运输单还有" + con.ToString() + "单";
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("异常：" + code + "运单无法找到或非在该派车单下！");
                    }
                }
            }
            else
            {
                throw new Exception("异常：未找到派车单或派车单已删除！");
            }
            return ss;
        }
        [WhereParameter]
        public string code { get; set; }

        public mapEvent MapSearch()
        {
            mapEvent map = new mapEvent();
            IDataAction action = this.model.GetDataAction();
            EntityList<ST_OutNotice> list = new EntityList<ST_OutNotice>(action);
            list.GetData("code='" + code + "' or ReceiptCode='" + code + "'");
            if (list.Count > 0)
            {
                ST_OutNotice on = list[0];
                ST_PackList pack = on.GetForeignObject<ST_PackList>(this.model.GetDataAction());
                map.sj = pack.GetAppendPropertyValue("TheDriver").ToString();
                map.yd = on.ReceiptCode;
                map.kh = on.GetAppendPropertyValue("CLIENTNO").ToString();
                map.lxr = on.GetAppendPropertyValue("ReceiptContactPerson").ToString();
                map.lxdh = on.ReceiptPhoneCode;
                map.dz = on.ReceiptAddress;
                map.ydzt = on.STATE.ToString();
                map.qxzt=on.ReceiptState.ToString();
                if (map.qxzt == "1")
                {
                    string simg = "select ReceiptImage from " + new ST_OutNotice().ToString() + " where id=" + on.ID;
                    object img = action.GetValue(simg);
                    if (img != null)
                    {
                        map.image=img.ToString();
                        //map.image = ConvertBytesToHex((byte[])img, false);
                    }
                }
                map.remark = on.Remark;
                string sql = "select top 1 *  from ST_TransportCoordinates where ParentID={0} order by id desc ";
                DataTable table = this.model.GetDataAction().GetDataTable(string.Format(sql, pack.ID));
                if (table != null && table.Rows.Count > 0)
                {
                    map.dwsj = table.Rows[0]["TransportTime"].ToString();
                    map.X = table.Rows[0]["X"].ToString();
                    map.Y = table.Rows[0]["Y"].ToString();
                }

            }
            else
            {
                throw new Exception("异常：查询的运单号不存在！");
            }
            return map;
        }
        protected string ConvertBytesToHex(byte[] arrByte, bool reverse)
        {
            StringBuilder sb = new StringBuilder();
            if (reverse)
                Array.Reverse(arrByte);
            foreach (byte b in arrByte)
                sb.AppendFormat("{0:x2}", b);
            return sb.ToString();
        }
        [WhereParameter]
        public string rimp { get; set; }
        [WhereParameter]
        public string cs { get; set; }
        private string impwz { get; set; }
        public string receipt()
        {
            if (!string.IsNullOrEmpty(code))
            {
                if (!string.IsNullOrEmpty(rimp))
                {
                    if (cs != "0")
                    {
                        impwz += rimp;
                        return cs;
                    }
                    else
                    {
                        impwz += rimp;
                        rimp = impwz;
                        cs = "0";
                        impwz = "";
                    }
                    rimp = System.Web.HttpUtility.UrlDecode(rimp);
                    string sql = "select a.id from Acc_WMS_OutNotice a,ST_PackList b where"
                        + " a.packid=b.id and a.receiptcode='" + code + "' and b.TheDriver=" + this.user.ID;//and a.ReceiptState=0 
                    IDataAction action = this.model.GetDataAction();
                    object id = action.GetValue(sql);
                    if (id != null && !string.IsNullOrEmpty(id.ToString()))
                    {
                        string us = "update Acc_WMS_OutNotice set ReceiptState=1,ReceiptImage='" + rimp + "' where id=" + id;
                        action.Execute(us);
                        return "0";
                    }
                    else
                    {
                        throw new Exception("异常：签收单号不正确或不是由" + this.user.name + "运输，不能签收！");
                    }
                }
                else
                {
                    throw new Exception("异常：签收单图片不能为空！");
                }
            }
            else
            {
                throw new Exception("异常：签收单条码不能为空！");
            }
        }
        public class mapEvent
        {
            /// <summary>
            /// 司机
            /// </summary>
            public string sj { get; set; }
            /// <summary>
            /// 运单条码
            /// </summary>
            public string yd { get; set; }
            /// <summary>
            /// 客户
            /// </summary>
            public string kh { get; set; }
            /// <summary>
            /// 联系人
            /// </summary>
            public string lxr { get; set; }
            /// <summary>
            /// 联系电话
            /// </summary>
            public string lxdh { get; set; }
            /// <summary>
            /// 地址
            /// </summary>
            public string dz { get; set; }
            public string remark { get; set; }
            /// <summary>
            /// 定位时间
            /// </summary>
            public string dwsj { get; set; }
            /// <summary>
            /// 运单状态
            /// </summary>
            public string ydzt { get; set; }
            /// <summary>
            /// 签收状态
            /// </summary>
            public string qxzt { get;set; }
            public string image { get; set; }
            public string X { get; set; }
            public string Y { get; set; }
        }
    }
}

